package common

import (
	"GoAdmin/model"
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	"log"
)

var DB *gorm.DB

func InitDB() *gorm.DB {
	//初始化相关属性
	drivername := viper.GetString("datasource.driverName")
	host := viper.GetString("datasource.host")
	port := viper.GetString("datasource.port")
	databases := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")

	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		username,
		password,
		host,
		port,
		databases,
		charset)

	log.Printf(args)
	//打开数据库
	db, err := gorm.Open(drivername, args)

	if err != nil {
		panic("连接数据库失败,err: " + err.Error())
	}
	//自动创建数据库表
	db.AutoMigrate(&model.User{})
	DB = db
	return db
}

func GetDB() *gorm.DB {
	return DB
}
